﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
using ThridGroup.ERP.DTO.WarehouseManagement;
using ThridGroup.ERP.WarehouseManagement;

namespace ThridGroup.ERP.Web.Controllers.WarehouseManagement
{
    [Route("WarehouseManagement/InventoryModel/[action]")]
    public class InventoryModelController : Controller
    {
        private readonly IInventoryModelServices _inventoryModelServices;
        private readonly ILogger<InventoryModelController> _logger;

        public InventoryModelController(
            IInventoryModelServices inventoryModelServices,
            ILogger<InventoryModelController> logger)
        {
            _inventoryModelServices = inventoryModelServices;
            _logger = logger;
        }

        /// <summary>
        /// 库存现有量页面
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            _logger.LogInformation("访问库存现有量页面");
            return View("~/Views/WarehouseManagement/InventoryModelView.cshtml");
        }

        /// <summary>
        /// 获取库存现有量列表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetList([FromQuery] QueryInventoryDto query)
        {
            try
            {
                _logger.LogInformation($"开始获取库存现有量列表，查询条件：{System.Text.Json.JsonSerializer.Serialize(query)}");

                var result = await _inventoryModelServices.GetInventoryListAsync(query);

                _logger.LogInformation($"成功获取库存现有量列表，共{result.TotalCount}条记录");

                return Json(new
                {
                    code = 0,
                    msg = "获取成功",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取库存现有量列表失败");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取库存详情
        /// </summary>
        /// <param name="id">库存ID</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get(int id)
        {
            try
            {
                _logger.LogInformation($"开始获取库存详情，ID：{id}");

                if (id <= 0)
                {
                    _logger.LogWarning($"无效的库存ID：{id}");
                    return Json(new { code = 1, msg = "无效的ID" });
                }

                var result = await _inventoryModelServices.GetInventoryByIdAsync(id);
                if (result == null)
                {
                    _logger.LogWarning($"未找到指定的库存记录，ID：{id}");
                    return Json(new { code = 1, msg = "未找到指定的库存记录" });
                }

                _logger.LogInformation($"成功获取库存详情，ID：{id}");
                return Json(new { code = 0, msg = "", data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取库存详情失败，ID：{id}");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取物料分类树形结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetMaterialTypeTree()
        {
            try
            {
                _logger.LogInformation("开始获取物料分类树形结构");

                var result = await _inventoryModelServices.GetMaterialTypeTreeAsync();

                _logger.LogInformation($"成功获取物料分类树形结构，共{result?.Count ?? 0}个根节点");

                return Json(new
                {
                    code = 0,
                    msg = "获取成功",
                    data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料分类树形结构失败");
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 获取库存统计信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> GetInventoryStats()
        {
            try
            {
                _logger.LogInformation("开始获取库存统计信息");

                // 创建一个查询所有数据的参数对象
                var allQuery = new QueryInventoryDto 
                { 
                    Page = 1, 
                    Limit = int.MaxValue // 获取所有数据用于统计
                };

                var result = await _inventoryModelServices.GetInventoryListAsync(allQuery);

                var stats = new
                {
                    TotalCount = result.TotalCount,
                    ValidCount = result.Items.Count(x => x.InventoryValidity),
                    InvalidCount = result.Items.Count(x => !x.InventoryValidity),
                    TotalQuantity = result.Items.Sum(x => x.QuantityInStock),
                    LowStockCount = result.Items.Count(x => x.QuantityInStock <= 10)
                };

                _logger.LogInformation($"成功获取库存统计信息：总计{stats.TotalCount}条，有效{stats.ValidCount}条，无效{stats.InvalidCount}条");

                return Json(new
                {
                    code = 0,
                    msg = "获取成功",
                    data = stats
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取库存统计信息失败");
                return Json(new { code = 1, msg = "获取统计信息失败：" + ex.Message });
            }
        }

        /// <summary>
        /// 导出库存数据
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ExportInventory([FromQuery] QueryInventoryDto query)
        {
            try
            {
                _logger.LogInformation($"开始导出库存数据，查询条件：{System.Text.Json.JsonSerializer.Serialize(query)}");

                // 设置较大的限制以获取所有匹配的数据
                query.Limit = int.MaxValue;
                query.Page = 1;

                var result = await _inventoryModelServices.GetInventoryListAsync(query);

                _logger.LogInformation($"准备导出{result.TotalCount}条库存记录");

                // TODO: 实现实际的Excel导出功能
                // 这里暂时返回JSON格式的数据，实际应用中可以使用NPOI或EPPlus等库生成Excel文件

                return Json(new
                {
                    code = 0,
                    msg = "导出成功",
                    data = result.Items,
                    count = result.TotalCount
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出库存数据失败");
                return Json(new { code = 1, msg = "导出失败：" + ex.Message });
            }
        }
    }
}
